/*homepage*/
function one(){
    loadPage("/server/baseServer")
}
function tow(){
    loadPage("/server/buildRecord")
}
function three(){
    loadPage("/server/buildAuditList")
}
function four(){
    loadPage("/server/buildApply")
}
function zhuxiao(){
    var storage = window.localStorage;
    storage.clear();
}
// 首页轮播图
layui.use(['carousel', 'form'], function(){
    var carousel = layui.carousel
        ,form = layui.form;

    //常规轮播
    carousel.render({
        elem: '#test1'
        ,width: '540px'
        ,height: '350px'
        ,arrow: 'always'
        ,autoplay: true

    });
});

// 首页选择测试环境弹出框
layui.use('layer', function(){
    var $ = layui.jquery, layer = layui.layer;

    //触发事件
    var active = {
        confirmTrans: function(){
            //配置一个透明的询问框
            layer.msg('请选择测试环境', {
                time: 20000, //20s后自动关闭
                btn: ['α', 'β','sit' ,'关闭'],
                yes: function(){
                    window.open("http://139.224.170.14:8090/login/");
                },
                btn2: function () {
                    window.open("http://101.132.163.225:8090/login/");
                },
                btn3: function () {
                    window.open("http://106.14.200.76:8090/login/");
                },
                btn4: function () {
                    layer.closeAll();
                }
            });
        }
    };

    $('#layerDemo .layui-btn').on('click', function(){
        var othis = $(this), method = othis.data('method');
        active[method] ? active[method].call(this, othis) : '';
    });
    $('.layui-btn').on('click', function(){
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });
});


/*Case List页面*/

// 主Table
layui.use('table', function(){

    var table = layui.table,$ = layui.jquery;

    // Table属性
    var opt={
        elem: '#table'
        ,url:'/api/cases/getCaseForPaging'
        ,cellMinWidth: 80
        ,page: true
        ,cols: [[
            {field: 'select', type:'checkbox', fixed: 'left'}
            ,{field:'id', title: 'ID', sort: true, align:'center', width: 60}
            ,{field:'chinese', title: '中文说明', align:'center', width: 260}
            ,{field:'signature', title: '验签', align:'center', width: 80, templet: '#signatureCheckboxTpl', unresize: true}
            ,{field:'module', title: '模块', sort: true, align:'center', width: 100}
            ,{field:'method', title: '方法', sort: true, align:'center', width: 80}
            // ,{field:'name', title: '用例名称', align:'center', width: 250}
            ,{field:'url', title: 'URL', align:'center', minWidth: 300}
            // ,{field:'body', title: 'Body', align:'center', templet: '#bodyTpl'}
            ,{field:'status', title: '启用', align:'center', width: 80, templet: '#checkboxTpl', unresize: true}
            ,{field:'shouldbe', title: '成功断言', align:'center', width: 200}
            ,{fixed: 'right', width:240, align:'center', toolbar: '#barDemo'}
        ]],
        where: {
            ID: 0,
            module: '',
            selectType: '0'
        },
        request: {
            //页码的参数名称，默认：page
            pageName: 'pageNumber',
            //每页数据量的参数名，默认：limit
            limitName: 'pageSize'
        },
        response: {
            //数据总数的字段名称，默认：count
            countName: 'total',
            //数据列表的字段名称，默认：data
            dataName: 'rows'
        }
    };

    // 渲染Table
    var tableIns = table.render(opt);
    table.on('sort(table)', function (obj) {
        tableIns.reload({
            initSort: obj,
            where: {
                sortName: obj.field,
                sortOrder: obj.type,
                //页码的参数名称，默认：page
                pageName: 'pageNumber',
                //每页数据量的参数名，默认：limit
                limitName: 'pageSize'
            }
        })
    });

    var $ = layui.$, active = {
        /*表格重载*/
        reload: function(){
            var idReload = $('#idReload');
            var moduleReload = $('#moduleSelect2');

            table.reload('table', {
                page: {
                    curr: 1 //重新从第 1 页开始
                }
                ,where: {
                    ID: idReload.val(),
                    module: moduleReload.val(),
                    selectType: "1"
                }
            });
        },

        /*运行选定Case实现*/
        getCheckData: function(){

            var checkStatus = table.checkStatus('table')
                ,data = checkStatus.data;

            if (data.length > 0) {

                // 获取ID
                var parms = "";

                data.forEach(function (e) {
                    parms = parms + e["id"] + ",";
                });
                parms = parms.substring(0, parms.length - 1);

                var env = $("#envSelect").val();

                $.get(
                    "/api/cases/runSingle", {
                        ids: parms,
                        env: env
                    }, function (data) {

                        if (data == "true") {
                            layer.alert("成功!30秒钟后可查看报告")
                        } else {
                            layer.alert("失败了!")
                        }

                    }
                )
            } else {
                layer.alert("还没有选中的Case!");
            }
        }
    };

    $('.demoTable .layui-btn').on('click', function(){
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });

    $('.layui-btn').on('click', function(){
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });


    // Table 工具栏
    table.on('tool(table)', function(obj){
        var data = obj.data;

        // Case详情 & Mock & 删除 & 备注
        if(obj.event === 'detail'){
            loadPageWithBlank("/case/detail?caseID=" + data.id)
        } else if(obj.event === 'del'){
            layer.confirm('真的删除行么', function(index){

                $.ajax({
                    type: "get",
                    url: "/api/cases/delete?caseID=" + data.id,
                    success: function(data) {
                        loadPage("/case/allCases");
                    }
                })

            });
        } else if (obj.event === "mock") {

            var env = $("#envSelect").val();

            // loading弹出
            var loading = layer.load(1);

            $.ajax({
                url: "/api/cases/mock",
                dataType: "json",
                async: true,
                data: { "caseID": data.id, "env": env},
                type: "GET",
                success: function(data) {
                    // 关闭loading
                    layer.closeAll('loading');

                    // var ss = JSON.parse(data);
                    var formattedStr = JSON.stringify(data, undefined, 4);
                    var formattedStrStr = highLight(formattedStr);

                    layui.use('layer', function () {
                        var layer = layui.layer;
                        layer.open({
                            type: 1,
                            area: ['800px', '600px'],
                            content: "<pre><br/>" + formattedStrStr + "<br/></pre>"
                        });
                    })
                },
                complete: function() {
                    //请求完成的处理
                },
                error: function(jqXHR, exception) {
                    // 关闭loading
                    layer.closeAll('loading');

                    var msg = '';
                    if (jqXHR.status === 0) {
                        msg = 'Not connect.\n Verify Network.';
                    } else if (jqXHR.status == 404) {
                        msg = '404了!';
                    } else if (jqXHR.status == 500) {
                        msg = '500了!';
                    } else if (exception === 'parsererror') {
                        msg = '失败了! 请检查环境是否正确!';
                    } else if (exception === 'timeout') {
                        msg = '超时了!';
                    } else if (exception === 'abort') {
                        msg = '请求中断了!';
                    } else {
                        msg = 'Uncaught Error.\n' + jqXHR.responseText;
                    }
                    layer.alert(msg);
                }
            });
        } else if (obj.event === "remark") {
            var data = obj.data;

            $.get(
                "/api/cases/getCaseRemark",{
                    caseID: data.id
                }, function (data) {
                    layer.open({
                        type: 1,
                        skin: 'layui-layer-rim',
                        area: ['540px', '350px'],
                        content: '<textarea readonly="readonly" style="height: 400px;" name="remark" class="layui-textarea">' + data + '</textarea>'
                    });
                }
            )
        }
    });

});



// serializeObject
function serializeObject(form){
    var o ={};
    $.each(form.serializeArray(),function(index){
        if(o[this['name']]){
            o[this['name']] = o[this['name']] +","+this['value'];

        }else{
            o[this['name']] = this['value'];
        }
    });
    return o;
}

// 高亮显示返回JSON
function highLight(json){
    json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
        var cls = 'number';
        if (/^"/.test(match)) {
            if (/:$/.test(match)) {
                cls = 'key';
            } else {
                cls = 'string';
            }
        } else if (/true|false/.test(match)) {
            cls = 'boolean';
        } else if (/null/.test(match)) {
            cls = 'null';
        }
        return '<span class="' + cls + '">' + match + '</span>';
    });
}



// 获取下拉框(模块)数据并填充
$.get(
    "/api/module/getModuleForPaging", {
        pageNumber: 1,
        pageSize: 10,
    }, function (data) {

        var objectD = JSON.parse(data);

        /*填充下拉框*/
        var storage = window.localStorage;
        var name =storage.username;
        var results ='<div>'+name+'    <a href="/server/userLoginPage" onclick="zhuxiao()">注销</a>'+'</div>';
        $('#退出1').append(results);
        $('#退出2').append(results);
        $('#退出3').append(results);
        $.each (objectD.rows, function (key, value) {
            var result = '<option value="' + value.name + '">' + value.name + '</option>';
            $('#moduleSelect').append(result);
            $('#moduleSelect2').append(result);
            $('#module').append(result);
        })
        /*刷新form, 包括样式和下拉框*/
        layui.use('form', function(){
            //只有执行了这一步，部分表单元素才会自动修饰成功
            var form = layui.form;
            form.render();
        });
    }
)
//服务类型
$.get(
    "/server/baseServerSelect", {
        pageNumber: 1,
        pageSize: 10,
    }, function (data) {
        var objectD = JSON.parse(data);
        $.each (objectD.rows, function (key, value) {
            var result = '<option value="' + value.vServer + '">' + value.vServer + '</option>';
            $('#BaseServerType').append(result);
        })
        layui.use('form', function(){
            var form = layui.form;
            form.render();
        });
    }
)

//获取部署方式
$.get(
    "/server/deploySelect", {
        pageNumber: 1,
        pageSize: 10,
    }, function (data) {
        var objectD = JSON.parse(data);
        $.each (objectD.rows, function (key, value) {
            var result = '<option value="' + value.vDeployType + '">' + value.vDeployType + '</option>';
            var result2 = '<option value="' + value.vDeployUrl + '">' + value.vDeployUrl + '</option>';
            $('#vDeployUrlSelect').append(result2);
            $('#vDeployTypeSelect').append(result);
        })
        layui.use('form', function(){
            var form = layui.form;
            form.render();
        });
    }
)
//开发语言相关
$.get(
    "/server/languageSelect", {
        pageNumber: 1,
        pageSize: 10,
    }, function (data) {

        var objectD = JSON.parse(data);

        /*填充下拉框*/
        $.each (objectD.rows, function (key, value) {
            var result = '<option value="' + value.vLanguage + '">' + value.vLanguage + '</option>';
            $('#vLanguageSelect').append(result);
        })
        layui.use('form', function(){
            var form = layui.form;
            form.render();
        });
    }
)
//获取系统类型
$.get(
    "/server/systemSelect", {
        pageNumber: 1,
        pageSize: 10,
    }, function (data) {

        var objectD = JSON.parse(data);

        /*填充下拉框*/
        $.each (objectD.rows, function (key, value) {
            var result = '<option value="' + value.vSystem + '">' + value.vSystem + '</option>';
            $('#vSystemSelect').append(result);
            $('#SystemType').append(result);
        })
        layui.use('form', function(){
            var form = layui.form;
            form.render();
        });
    }
)

// 运行全部Case
function clickRunAll() {

    var env = $("#envSelect").val();

    $.get(
        "/api/cases/runAll", {
            env: env
        }, function (data) {

            if (data == "true"){
                layer.alert("成功!30秒钟后可查看报告")
            } else {
                layer.alert("失败了!")
            }
        }
    )
}

// 运行模块Case
function clickRunModule() {

    var moduleName = $("#moduleSelect").val();
    var env = $("#envSelect").val();

    if (moduleName == "" || moduleName == null) {
        layer.alert("未选择模块!");
        return;
    }

    $.get(
        "/api/cases/runModule", {
            moduleName: moduleName,
            env: env
        }, function (data) {

            if (data == "true"){
                layer.alert("成功!30秒钟后可查看报告")
            } else {
                layer.alert("失败了!")
            }
        }
    )
}

// 运行清理SQL
function clickRunModuleSQL() {

    var moduleName = $("#moduleSelect").val();
    var env = $("#envSelect").val();

    if (moduleName == "" || moduleName == null) {
        layer.alert("未选择模块!");
        return;
    }

    $.get(
        "/api/cases/runModuleSQL", {
            moduleName: moduleName,
            env: env
        }, function (data) {

            if (data == "true"){
                /*待添加文字说明, 以及alert框的样式*/
                layer.alert("脚本执行成功!")
            } else if (data == "no"){
                layer.alert("未查询到脚本!")
            } else {
                layer.alert("脚本执行失败!")
            }
        }
    )
}

// 载入页面(From当前网页)
function loadPage(url) {
    window.location.href = url;
}

// 载入页面(打开新网页)
function loadPageWithBlank(url) {
    window.open(url);
}